<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
Yii::import('system.web.widgets.CWidget');
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
Zend_Loader::loadClass('Zend_Http_Client');

class googlecalendar extends CWidget {

    public $user;
    public $pass;
    public $service;
    public $client;
    public $eventId;
    public $newTitle;
    private $_baseUrl;
	
	public function login($glog,$gpass) {
        $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
        $client = Zend_Gdata_ClientLogin::getHttpClient($glog,$gpass,$service);
        return $client;
    }

    public function doEvents($action,$id,$glogin,$gpassword) {
		$client = $this->login($glogin,$gpassword);
		
		if ($action == "update") {
			$gcal = new Zend_Gdata_Calendar($client);
			$query = $gcal->newEventQuery();
			$query->setUser('default');
			$query->setVisibility('private');
			$query->setProjection('full');
			$query->setEvent($id);
			
			try {          
				$eventEntry = $gcal->getCalendarEventEntry($query);
			} catch (Zend_Gdata_App_Exception $e) {
				echo "Error: " . $e->getResponse();
				return null;
			}
			
			$this->render('edit', array('event' => $eventEntry, 'id' => $id));
		}
		else if ($action == "delete") {
			$this->render('delete', array('id' => $id));
		}
		else {
			$events = $this->outputCalendar($client);
			$this->render('view', array('events' => $events));
		}
		
		if (isset($_POST['submit'])) {
            $title = $_POST['createevent'];
			$startDate = $_POST['startdate'];
			$pieces1 = explode(" ", $startDate); 
			$startDate = $pieces1[0];
			$startTime = $pieces1[1]; 
            $endDate = $_POST['enddate'];
			$pieces2 = explode(" ", $endDate); 
			$endDate = $pieces2[0];
            $endTime = $pieces2[1];
			$meeting_location = $_POST['meeting_location'];
			$desc = $_POST['desc'];
			$descr = "Место проведения: " . $meeting_location . "\nОписание: " . $desc;
            $tzOffset = '+04';
			$gflag = 0;
			
			if (isset($_POST['guests'])) {
				$guests = $_POST['guests'];
				
				foreach ($guests as $guest) {
					if ($guest == "input") {
						$gflag = 1;
					}
				}
				if ($gflag == 1) {
					$gflag = 0;
					$guests2 = $_POST['guests2'];
					$from_name = $_POST['from_name'];
					if (strlen($from_name) == '') {
						$from_name = 'invite';
					}
					$mtext = $_POST['mtext']; 
					$sendemail = $this->sendIcal($from_name, $title, $startDate, $startTime, $endDate, $endTime, $meeting_location, $desc, $mtext, $guests2);
					if (!preg_match("/0/i", $sendemail)) {
						Yii::app()->user->setFlash('successl',"Сообщение успешно отправлено!");
					}
					else {
						Yii::app()->user->setFlash('fails',"Ошибка при отправке сообщения");
						//Yii::app()->user->setFlash('fails',$sendemail);
					}
				}
			}
			
			if (strlen($title) == '') {
				$title = 'no title';
			}
			if (($startDate != '') && ($endDate != '')) {
				$createevent = $this->createEvent($client, $title, $descr, $startDate, $startTime, $endDate, $endTime, $tzOffset, $guests);
			}		
			
            if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
                $protocol = 'https://';
            } else {
                $protocol = 'http://';
            }
            $url = $protocol . Yii::app()->getRequest()->serverName . Yii::app()->getRequest()->requestUri;
            header('Location:' . $url);
        }
		
		if (isset($_POST['update'])) {
            $new_title = $_POST['title'];
			$new_sdate = $_POST['startdate'];
			$new_edate = $_POST['enddate'];
			$new_descr = $_POST['desc'];
			
			if (isset($_POST['guests'])) { 
			  $guests = $_POST['guests'];
			}  
			else {
				$guests = "";
			}
			
            $id = $_POST['id'];
            if ($new_title != '') {
                $updateevent = $this->updateEvent($client, $id, $new_title, $new_sdate, $new_edate, $new_descr, $guests);
            }
			
			Yii::app()->user->setFlash('successu',"Событие успешно обновлено!");
			
            if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
                $protocol = 'https://';
            } else {
                $protocol = 'http://';
            }
            $url = $protocol . Yii::app()->getRequest()->serverName . Yii::app()->getRequest()->requestUri;
            header('Location:' . $url);
        }
		
		if (isset($_POST['delete'])) {			   
			$id = $_POST['id'];
			$this->deleteEventById($client, $id);
			
			Yii::app()->user->setFlash('successd',"Событие успешно удалено!");
			
			if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
				$protocol = 'https://';
			} else {
				$protocol = 'http://';
			}
            $url = $protocol . Yii::app()->getRequest()->serverName . Yii::app()->getRequest()->requestUri;
            header('Location:' . $url);
		}
    }

    function outputCalendar($client) {
        $gdataCal = new Zend_Gdata_Calendar($client);
        $query = $gdataCal->newEventQuery();
		$query->setUser('default');
		$query->setVisibility('private');
		$query->setProjection('full');
		try {
			$eventFeed = $gdataCal->getCalendarEventFeed($query);
		} catch (Zend_Gdata_App_Exception $e) {
		echo "Error: " . $e->getResponse();
		}
        return $eventFeed;
    }

    function createEvent($client, $title, $descr, $startDate, $startTime, $endDate, $endTime, $tzOffset, $guests) {
        $gdataCal = new Zend_Gdata_Calendar($client);
        $newEvent = $gdataCal->newEventEntry();

        $newEvent->title = $gdataCal->newTitle($title);
        $newEvent->content = $gdataCal->newContent($descr);
		
		$reminder = $gdataCal->newReminder();
		$reminder->method = "email";
		$reminder->minutes = "15";
		
		if (is_array($guests)) {
			while (list(,$mail) = each($guests)) {
				if ($mail == "input") { continue; }
				$who = $gdataCal->newWho(); 
				$who->setEmail($mail); 
				$status = new Zend_Gdata_Extension_AttendeeStatus();
				$status->setValue("http://schemas.google.com/g/2005#event.accepted");
				$who->setAttendeeStatus($status);
				$whoArray[] = $who;
			}
			if (is_array($whoArray)) { 
				$newEvent->setWho($whoArray); 
			}
		}
		
		$sendEventNotifications = new Zend_Gdata_Calendar_Extension_SendEventNotifications();
		$sendEventNotifications->setValue(true);
		$newEvent->setSendEventNotifications($sendEventNotifications);

        $when = $gdataCal->newWhen();
        $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
        $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
		$when->reminders = array($reminder);
        $newEvent->when = array($when);
        $createdEvent = $gdataCal->insertEvent($newEvent);
        return $createdEvent->id->text;
    }

    public function getEvent($client, $eventId) {		
		$gcal = new Zend_Gdata_Calendar($client);
        $query = $gcal->newEventQuery();
        $query->setUser('default');
        $query->setVisibility('private');
        $query->setProjection('full');
        $query->setEvent($eventId);
		try {          
			$eventEntry = $gcal->getCalendarEventEntry($query);
			return $eventEntry;
        } catch (Zend_Gdata_App_Exception $e) {
			echo "Error: " . $e->getResponse();
			return null;
        }
		
    }
	
	function deleteEventById($client, $paramid) {
        $event = $this->getEvent($client, $paramid);
        $event->delete();
    }
	
	public function updateEvent($client, $eventId, $newTitle, $newSDate, $newEDate, $newDescr, $guests) {
        $gdataCal = new Zend_Gdata_Calendar($client);
        $eventOld = $this->getEvent($client, $eventId);
		
        if ($eventOld) {
            $eventOld->title = $gdataCal->newTitle($newTitle);
			$eventOld->content = $gdataCal->newContent($newDescr);
			$pieces1 = explode(" ", $newSDate); 
			$startDate = $pieces1[0];
			$startTime = $pieces1[1]; 
			$pieces2 = explode(" ", $newEDate); 
			$endDate = $pieces2[0];
            $endTime = $pieces2[1];
			$tzOffset = '+04';
			$reminder = $gdataCal->newReminder();
			$reminder->method = "email";
			$reminder->minutes = "15";
			
			if (is_array($guests)) {
				while (list(,$mail) = each($guests)) {
					if ($mail == "input") { continue; }
					$who = $gdataCal->newWho(); 
					$who->setEmail($mail); 
					$status = new Zend_Gdata_Extension_AttendeeStatus();
					$status->setValue("http://schemas.google.com/g/2005#event.accepted");
					$who->setAttendeeStatus($status);
					$whoArray[] = $who;
				}
				if (is_array($whoArray)) { 
					$eventOld->setWho($whoArray); 
				}
			}
			
			$sendEventNotifications = new Zend_Gdata_Calendar_Extension_SendEventNotifications();
			$sendEventNotifications->setValue(true);
			$eventOld->setSendEventNotifications($sendEventNotifications);
			
			$when = $gdataCal->newWhen();
			$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
			$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
			$when->reminders = array($reminder);
			$eventOld->when = array($when);
            try {
                $eventOld->save();
            } catch (Zend_Gdata_App_Exception $e) {
                echo "Error: " . $e;
                return null;
            }
            $eventNew = $this->getEvent($client, $eventId);
            return $eventNew;
        } else {
            return null;
        }
    }
	
	function sendIcal($from_name, $title, $startDate, $startTime, $endDate, $endTime, $meeting_location, $desc, $mtext, $guests2) {	
		$from_address = "denis@elcp.ru";
		$tzOffset = '+04';
		//Convert MYSQL datetime and construct iCal start, end and issue dates
        $dtstart = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
        $dtend = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";		
		//$meetingstamp = STRTOTIME($model->meeting_date . " UTC");    
		//$dtstart= GMDATE("Ymd\THis\Z",$meetingstamp);
		//$dtend= GMDATE("Ymd\THis\Z",$meetingstamp+$meeting_duration);
		$todaystamp = GMDATE("Ymd\THis\Z");
	 
		//Create unique identifier
		$cal_uid = DATE('Ymd').'T'.DATE('His')."-".RAND()."@mydomain.com";
	 
		//Create Mime Boundry
		$mime_boundary = "----Meeting Booking----".MD5(TIME());
	 
		//Create Email Headers
		$headers = "From: ".$from_name." <".$from_address.">\n";
		$headers .= "Reply-To: ".$from_name." <".$from_address.">\n";
	 
		$headers .= "MIME-Version: 1.0\n";
		$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
		$headers .= "Content-class: urn:content-classes:calendarmessage\n";
	 
		//Create Email Body (HTML)
		$message = "";
		$message .= "--$mime_boundary\n";
		$message .= "Content-Type: text/html; charset=UTF-8\n";
		$message .= "Content-Transfer-Encoding: 8bit\n\n";
	 
		$message .= "<html>\n";
		$message .= "<body>\n";
		$message .= '<p>'.$mtext.'</p>';   
		$message .= "</body>\n";
		$message .= "</html>\n";
		$message .= "--$mime_boundary\n";
			 
$ical = 'BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:'.$from_address.'
DTSTART:'.$dtstart.'
DTEND:'.$dtend.'
LOCATION:'.$meeting_location.'
TRANSP:OPAQUE
SEQUENCE:0
UID:'.$cal_uid.'
DTSTAMP:'.$todaystamp.'
DESCRIPTION:'.$desc.'
SUMMARY:'.$title.'
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR';   
			 
		$message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST\n';
		$message .= "Content-Transfer-Encoding: 8bit\n\n";
		$message .= $ical;            
		
		$ressm = "";
		$guest2send = explode("\n", $guests2); 	
		
		while (list($key,$email) = each($guest2send)) {
			//$ressm .= $key . "=>" . $email . "\n";
			$ressm .= @MAIL($email, $title, $message, $headers);
		}
		return $ressm;
	}	
}
?>
